package com.suse.ecommerce.uilts.crawler;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class HttpUtil {
	/**
     * post请求
     * @param url 请求地址
     * @param body 请求数据
     */
    public static String post(String url, String body){
        log.debug("http", "post url = "+url+"\n"+"body = "+body);
        StringBuilder result = new StringBuilder();
        OutputStreamWriter out = null;
        BufferedReader in = null;
        try{
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            //设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(200000);

            //提交数据
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();

            //读取返回数据
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            boolean firstLine = true; //读取第一行的时候不加换行符
            while((line = in.readLine()) != null){
                if(firstLine){
                    firstLine = false;
                }else{
                    result.append(System.lineSeparator());
                }
                result.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try{
                if(out != null)
                    out.close();
                if(in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return result.toString();
    }
    
    public static String get(String url) {
    	URL u = null;
    	BufferedReader reader = null;
    	URLConnection conn = null;
    	try {
    		u = new URL(url);
    		conn = u.openConnection();
    		// 设置请求属性
    		conn.setRequestProperty("accept", "*/*");
    		conn.setRequestProperty("connection", "Keep-Alive");
    		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    		conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    		
    		conn.connect();
    		StringBuffer buffer = new StringBuffer();
    		reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    		String line = null;
    		while((line = reader.readLine()) != null) {
    			buffer.append(line);
    		}
    		return buffer.toString();
    	}catch(Exception e) {
    		e.printStackTrace();
    	}finally {
    		if(reader != null) {
    			try {
    				reader.close();
    			}catch(IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	return "";
    }
}
